#include "BlockQueue.hpp"
#include "Task.hpp"
#include <ctime>

#define CNUM 3
#define PNUM 5
void *Consumer(void *args)
{
    // pthread_detach(pthread_self());
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(args);

    while (true)
    {
        // 消费
        Task t = bq->pop();

        // 计算
        // t.run()
        t();
        
        cout << "处理任务 " << t.GetTask() << " 运算结果是： " << t.GetResult() << " thread id: " << pthread_self() << endl;
        //sleep(1);
    }
}

void *Productor(void *args)
{
    // pthread_detach(pthread_self());
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(args);
    int len = opers.size();

    int x = 20;
    int y = 10;
    while (true)
    {
        // 模拟实现生产者生产数据
        int data1 = rand() % x + 1;
        usleep(10);
        int data2 = rand() % y;
        char op = opers[rand() % len];
        Task t(data1, data2, op);

        // 生产
        bq->push(t);
        
        cout << "生产了一个任务 " << t.GetTask() << " thread id: " << pthread_self() << endl;
        sleep(1);
    }
}

int main()
{
    srand(time(nullptr));

    // 这里不仅仅是只能传递内置类型，也可以传入自定义类型
    BlockQueue<Task> *bq = new BlockQueue<Task>();

    pthread_t c[3], p[5];

    for (int i = 0; i < CNUM; i++)
    {
        pthread_create(c + i, nullptr, Consumer, bq);
    }

    for (int i = 0; i < PNUM; i++)
    {
        pthread_create(p + i, nullptr, Productor, bq);
    }

    for (int i = 0; i < CNUM; i++)
    {
        pthread_join(c[i], nullptr);
    }

    for (int i = 0; i < PNUM; i++)
    {
        pthread_join(p[i], nullptr);
    }

    delete bq;
    return 0;
}